import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../controller/wallet_controller.dart';
import '../../model/wallet_model.dart';

class RecordsDetailPage extends StatefulWidget {
  const RecordsDetailPage({Key? key}) : super(key: key);

  @override
  _RecordsDetailPageState createState() => _RecordsDetailPageState();
}

class _RecordsDetailPageState extends State<RecordsDetailPage> with SingleTickerProviderStateMixin {
  late final WalletController walletController;
  final ScrollController _incomeScrollController = ScrollController();
  final ScrollController _withdrawScrollController = ScrollController();
  final RxBool _isLoadingMoreIncome = false.obs;
  final RxBool _isLoadingMoreWithdraw = false.obs;
  final RxInt _currentIncomePage = 1.obs;
  final RxInt _currentWithdrawPage = 1.obs;
  final int _pageSize = 20;
  
  late TabController _tabController;
  final RxInt _currentTabIndex = 0.obs;

  // 用于控制刷新指示器的键
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();

  @override
  void initState() {
    super.initState();
    try {
      walletController = Get.find<WalletController>();
    } catch (e) {
      walletController = Get.put(WalletController());
    }
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      _currentTabIndex.value = _tabController.index;
    });
    
    // 先加载初始数据
    _loadInitialData();
    _setupScrollListeners();
    
    // 添加自动下拉刷新功能，延迟执行以确保界面已经构建完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 使用 RefreshIndicator 的 key 来触发刷新
      _refreshIndicatorKey.currentState?.show();
    });
  }

  void _loadInitialData() {
    // 设置初始页码
    _currentIncomePage.value = 1;
    _currentWithdrawPage.value = 1;
    // 使用新的详情页面加载方法
    walletController.loadDetailIncomeRecords(page: 1);
    walletController.loadDetailWithdrawRecords(page: 1);
  }

  void _setupScrollListeners() {
    _incomeScrollController.addListener(() {
      if (_incomeScrollController.position.pixels >=
          _incomeScrollController.position.maxScrollExtent - 200) {
        _loadMoreIncomeData();
      }
    });
    
    _withdrawScrollController.addListener(() {
      if (_withdrawScrollController.position.pixels >=
          _withdrawScrollController.position.maxScrollExtent - 200) {
        _loadMoreWithdrawData();
      }
    });
  }

  Future<void> _loadMoreIncomeData() async {
    if (_isLoadingMoreIncome.value) return;
    
    _isLoadingMoreIncome.value = true;
    _currentIncomePage.value++;
    
    // 调用加载更多收益记录的API
    if (!walletController.isLoadingDetailIncomeRecords.value && 
        walletController.hasMoreIncomeRecords.value) {
      await walletController.loadDetailIncomeRecords(page: _currentIncomePage.value);
    }
    
    _isLoadingMoreIncome.value = false;
  }
  
  Future<void> _loadMoreWithdrawData() async {
    if (_isLoadingMoreWithdraw.value) return;
    
    _isLoadingMoreWithdraw.value = true;
    _currentWithdrawPage.value++;
    
    // 调用加载更多提现记录的API
    if (!walletController.isLoadingDetailWithdrawRecords.value && 
        walletController.hasMoreWithdrawRecords.value) {
      await walletController.loadDetailWithdrawRecords(page: _currentWithdrawPage.value);
    }
    
    _isLoadingMoreWithdraw.value = false;
  }

  Future<void> _onRefresh() async {
    if (_currentTabIndex.value == 0) {
      _currentIncomePage.value = 1;
    } else {
      _currentWithdrawPage.value = 1;
    }
    await walletController.refreshDetailData();
  }

  @override
  void dispose() {
    _incomeScrollController.dispose();
    _withdrawScrollController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  Widget _buildIncomeRecordsTab() {
    return RefreshIndicator(
      key: _refreshIndicatorKey,
      onRefresh: _onRefresh,
      backgroundColor: Color(0xFF2A2A2A),
      color: Colors.orange,
      child: Obx(() {
        final records = walletController.detailIncomeRecords;

        if (records.isEmpty && !walletController.isLoadingDetailIncomeRecords.value) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.inbox_outlined, color: Colors.grey[400], size: 48),
                SizedBox(height: 16),
                Text(
                  'No Records Available'.tr,
                  style: TextStyle(color: Colors.grey[400], fontSize: 16),
                ),
              ],
            ),
          );
        }

        return ListView.builder(
          controller: _incomeScrollController,
          physics: AlwaysScrollableScrollPhysics(),
          padding: EdgeInsets.all(16),
          itemCount: records.length + 1, // +1 for loading indicator
          itemBuilder: (context, index) {
            if (index < records.length) {
              return _buildRecordItem(records[index]);
            } else {
              // 底部加载更多指示器
              return Obx(() {
                if (_isLoadingMoreIncome.value) {
                  return Container(
                    padding: EdgeInsets.symmetric(vertical: 16),
                    alignment: Alignment.center,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
                    ),
                  );
                } else {
                  return SizedBox.shrink();
                }
              });
            }
          },
        );
      }),
    );
  }

  Widget _buildWithdrawRecordsTab() {
    return RefreshIndicator(
      onRefresh: _onRefresh,
      backgroundColor: Color(0xFF2A2A2A),
      color: Colors.orange,
      child: Obx(() {
        final records = walletController.detailWithdrawRecords;

        if (records.isEmpty && !walletController.isLoadingDetailWithdrawRecords.value) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.inbox_outlined, color: Colors.grey[400], size: 48),
                SizedBox(height: 16),
                Text(
                  'No Records Available'.tr,
                  style: TextStyle(color: Colors.grey[400], fontSize: 16),
                ),
              ],
            ),
          );
        }

        return ListView.builder(
          controller: _withdrawScrollController,
          physics: AlwaysScrollableScrollPhysics(),
          padding: EdgeInsets.all(16),
          itemCount: records.length + 1, // +1 for loading indicator
          itemBuilder: (context, index) {
            if (index < records.length) {
              return _buildRecordItem(records[index]);
            } else {
              // 底部加载更多指示器
              return Obx(() {
                if (_isLoadingMoreWithdraw.value) {
                  return Container(
                    padding: EdgeInsets.symmetric(vertical: 16),
                    alignment: Alignment.center,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
                    ),
                  );
                } else {
                  return SizedBox.shrink();
                }
              });
            }
          },
        );
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF1A1A1A),
      appBar: AppBar(
        backgroundColor: Color(0xFF1A1A1A),
        title: Text(
          'Recent Records'.tr,
          style: TextStyle(color: Colors.white),
        ),
        iconTheme: IconThemeData(color: Colors.white),
        elevation: 0,
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: Colors.orange,
          labelColor: Colors.orange,
          unselectedLabelColor: Colors.grey,
          labelStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          unselectedLabelStyle: TextStyle(fontSize: 16),
          tabs: [
            Tab(text: 'Income Records'),
            Tab(text: 'Withdrawal Records'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // 收益记录标签页
          _buildIncomeRecordsTab(),
          // 提现记录标签页
          _buildWithdrawRecordsTab(),
        ],
      ),
    );
  }

  Widget _buildRecordItem(RecentRecordModel record) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 12),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Color(0xFF2A2A2A), width: 0.5),
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: record.statusColor.withOpacity(0.2),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(record.typeIcon, color: record.statusColor, size: 20),
          ),
          SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  record.title,
                  style: TextStyle(color: Colors.white, fontSize: 14),
                ),
                SizedBox(height: 2),
                Text(
                  '${record.formattedDate} ${record.formattedTime}',
                  style: TextStyle(color: Colors.grey[400], fontSize: 12),
                ),
                if (record.remark != null && record.remark!.isNotEmpty) ...[
                  SizedBox(height: 2),
                  Text(
                    record.remark!,
                    style: TextStyle(color: Colors.red[300], fontSize: 11),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ],
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                '${record.displayAmount >= 0 ? '+' : ''}${record.displayAmount.toStringAsFixed(12)} BTC',
                style: TextStyle(
                  color: record.displayAmount >= 0 ? Colors.green : Colors.red,
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}